﻿using Microsoft.Extensions.DependencyInjection;
using Qianke.Core.Common.Interface;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using Volo.Abp;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Modularity;
using Volo.Abp.Uow;

namespace Qianke.Core.Common
{
    public static class SaasModuleServiceKeyNameRegistrar
    {

        public static void AddModuleServiceFromCallingAssembly(this IServiceCollection services)
        {
            var assembly =  Assembly.GetCallingAssembly();
            services.AddModuleServiceFromAssembly(assembly);
        }

        public static void AddModuleService<TAbpModule>(this IServiceCollection services)
        {
            services.AddModuleServiceFromAssembly(typeof(TAbpModule).Assembly);
        }

        public static void AddModuleServiceFromAssembly(this IServiceCollection services,Assembly assembly)
        {
            foreach (var type in assembly.GetTypes())
            {
                // 检查是否标记了 ServiceKeyName 属性
                var serviceKeyNameAttribute = type.GetCustomAttribute<ServiceKeyNameAttribute>();
                if (serviceKeyNameAttribute != null)
                {
                    // 根据 属性 进行自定义注册
                    RegisterService(services, type, serviceKeyNameAttribute);
                }
            }
        }

        private static void RegisterService(this IServiceCollection services, Type implementationType, ServiceKeyNameAttribute attr)
        {
            switch (attr.Lifetime)
            {
                case ServiceLifetime.Scoped:
                    services.AddKeyedScoped(attr.InfaceType, attr.Name, implementationType);
                    break;
                case ServiceLifetime.Singleton:
                    services.AddKeyedSingleton(attr.InfaceType, attr.Name, implementationType);
                    break;
                case ServiceLifetime.Transient:
                    services.AddKeyedTransient(attr.InfaceType, attr.Name, implementationType);
                    break;
                default:
                    throw new AbpException($"Unknown {nameof(ServiceLifetime)} value: {attr.Lifetime}");
            }
        }
    }
}
